#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
登录功能测试脚本
"""

import requests
import json
import time

def test_login():
    """测试登录功能"""
    base_url = "http://localhost:5001"
    
    # 测试用户列表
    test_users = [
        {"username": "admin", "password": "123456", "expected_role": "admin"},
        {"username": "student", "password": "123456", "expected_role": "student"},
        {"username": "teacher", "password": "123456", "expected_role": "teacher"},
        {"username": "wrong", "password": "wrong", "expected_role": None}  # 错误凭据
    ]
    
    print("🔐 测试登录功能")
    print("=" * 50)
    
    for i, user in enumerate(test_users, 1):
        print(f"\n📝 测试 {i}: {user['username']}")
        
        try:
            # 发送登录请求
            response = requests.post(
                f"{base_url}/login",
                json={
                    "username": user["username"],
                    "password": user["password"]
                },
                headers={"Content-Type": "application/json"}
            )
            
            if response.status_code == 200:
                data = response.json()
                if data.get("status") == "success":
                    print(f"✅ 登录成功: {user['username']}")
                    print(f"   重定向到: {data.get('redirect', 'N/A')}")
                else:
                    print(f"❌ 登录失败: {data.get('message', '未知错误')}")
            else:
                print(f"❌ HTTP错误: {response.status_code}")
                if response.text:
                    try:
                        error_data = response.json()
                        print(f"   错误信息: {error_data.get('message', '未知错误')}")
                    except:
                        print(f"   响应内容: {response.text[:100]}")
                        
        except requests.exceptions.ConnectionError:
            print("❌ 无法连接到服务器，请确保服务正在运行")
            return False
        except Exception as e:
            print(f"❌ 请求异常: {e}")
    
    return True

def test_protected_routes():
    """测试受保护的路由"""
    base_url = "http://localhost:5001"
    
    print("\n🔒 测试受保护的路由")
    print("=" * 50)
    
    # 测试未登录访问dashboard
    try:
        response = requests.get(f"{base_url}/dashboard")
        if response.status_code == 302:  # 重定向到登录页面
            print("✅ 未登录访问dashboard被正确重定向")
        else:
            print(f"❌ 未登录访问dashboard未重定向，状态码: {response.status_code}")
    except Exception as e:
        print(f"❌ 测试失败: {e}")
    
    # 测试未登录访问API
    try:
        response = requests.post(
            f"{base_url}/api/chat",
            json={"message": "test"},
            headers={"Content-Type": "application/json"}
        )
        if response.status_code == 302:  # 重定向到登录页面
            print("✅ 未登录访问API被正确重定向")
        else:
            print(f"❌ 未登录访问API未重定向，状态码: {response.status_code}")
    except Exception as e:
        print(f"❌ 测试失败: {e}")

def main():
    """主函数"""
    print("🚀 Rust知识解释智能体 - 登录功能测试")
    print("=" * 60)
    
    # 等待服务启动
    print("⏳ 等待服务启动...")
    time.sleep(2)
    
    # 测试登录功能
    if test_login():
        # 测试受保护的路由
        test_protected_routes()
    
    print("\n" + "=" * 60)
    print("🎯 测试完成！")
    print("📱 现在可以在浏览器中访问:")
    print("   🔐 登录页面: http://localhost:5001/login")
    print("   📊 主页面: http://localhost:5001/dashboard")
    print("\n👥 默认用户:")
    print("   管理员: admin / 123456")
    print("   学生:   student / 123456")
    print("   教师:   teacher / 123456")

if __name__ == "__main__":
    main() 